<?php

namespace App\Repositories\GameTool;


use App\Models\GameTool\RedPacket;
use App\Models\GameTool\RedPacketLog;

class RedPacketRepository
{
    public function create($data)
    {
        $redPacket = new RedPacket($data);
        $redPacket->account_type = $data['account_type'];
        $redPacket->stat_1_time = $data['stat_1_time'];
        $redPacket->error_msg = '';

        return $redPacket->save();
    }

    public function createLog($data)
    {
        $redPacket = new RedPacketLog($data);
        $redPacket->redpacket_id = $data['redpacket_id'];
        $redPacket->url = $data['url'];
        $redPacket->request_time = getCurrentTime();
        $redPacket->response = $data['response'];

        return $redPacket->save();
    }

    public function getAllRedPacket($request)
    {
        $query = RedPacket::query();
        $gameID = session('game_id');

        if ($request->has('start_time')) {
            $query->where('created_at', '>=', $request['start_time'] . ' 00:00:00');
        }
        if ($request->has('end_time')) {
            $query->where('created_at', '<=', $request['end_time'] . ' 23:59:59');
        }
        $query->where('game_id', '=', $gameID);

        if ($request->has('money_from') && $request['money_from'] > 0) {
            $query->where('money', '>=', $request['money_from']);
        }
        if ($request->has('money_to') && $request['money_to'] > 0) {
            $query->where('money', '<=', $request['money_to']);
        }
        if ($request->has('stat') && $request['stat'] > 0) {
            $query->where('stat', '=', $request['stat']);
        }
        if ($request->has('no') && $request['no'] > 0) {
            $query->where('no', '=', $request['no']);
        }
        if ($request->has('account') && !empty($request['account'])) {
            $query->where('account', '=', $request['account']);
        }
        if ($request->has('account_name') && !empty($request['account_name'])) {
            $query->where('account_name', '=', $request['account_name']);
        }
        if ($request->has('order_by') && !empty($request['order_by'])) {
            $query->orderBy($request['order_by'], $request['order_direction']);
        }

        return $query->paginate($request['page_size']);
    }

    public function getByID($id)
    {
        return RedPacket::find($id);
    }

    public function update(array $data, $id)
    {
        return RedPacket::query()->where('id', $id)->update($data);
    }
}